package com.df.excel_export.validator.vadator_impl.type_array;

import com.df.excel_export.common.ExcelTable;
import com.df.excel_export.validator.AbstractIFieldValidator;
import com.df.excel_export.validator.IFieldValidator;
import com.df.excel_export.validator.IValidatorFactory;
import com.df.excel_export.validator.vadator_impl.type_string.StringLenRangeValidator;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArrayLenRangeValidator extends AbstractIFieldValidator implements IValidatorFactory {
    public int min;
    public int max;
    @Override
    public boolean support(String filedType, String ruleStr) {
        String regex = "^(int|long|float|string)\\[\\]$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(filedType);
        if(!matcher.find()) {
            return false;
        }
        if(ruleStr.startsWith("len[") && ruleStr.endsWith("]")) {
            return true;
        }
        return false;
    }

    @Override
    public IFieldValidator create(String filedType, String ruleStr) {
        ArrayLenRangeValidator validator  = new ArrayLenRangeValidator();
        String trim = ruleStr.trim();
        String substring = trim.substring(4, trim.length() - 1);
        String[] split = substring.split(",");
        String minStr = split[0];
        String maxStr = split[1];
        if(minStr.equals("-")){
            validator.min = Integer.MIN_VALUE;
        }else {
            validator.min = Integer.parseInt(minStr);
        }
        if(validator.min<0){
            validator.min = 0;
        }
        if(maxStr.equals("-")){
            validator.max = Integer.MAX_VALUE;
        }else {
            validator.max = Integer.parseInt(maxStr);
        }
        if(validator.max<0){
            validator.max=0;
        }
        return validator;
    }

    @Override
    public Integer getPriority() {
        return 0;
    }

    @Override
    public boolean validate(ExcelTable checkTable, List<Object> rowData, Integer dataRowIndex, Integer fieldIndex, String fieldName, String fieldTypeStr, Object filedValue) {
        List<?> value = (List<?>) filedValue;
        if(value.size()<min || value.size()>max){
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String ruleStr = "int[]";
        String regex = "^(int|long|float|string)\\[\\]$";
//        String regex = "(int|long|float|string)\\[\\]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ruleStr);
        if(matcher.find()) {
            String group = matcher.group(0);
            System.out.println("匹配成功:"+group);
        }
    }
}
